<template>
  <div style="padding: 20px">
    <!-- 操作区域 -->
    <el-autocomplete
      popper-class="my-autocomplete"
      v-model="statetype"
      :fetch-suggestions="querySearch"
      placeholder="请选择搜索的类型"
      @select="handleSelect"
      style="width: 180px; margin-right: 20px"
    >
      <i
        class="el-icon-edit el-input__icon"
        slot="suffix"
        @click="handleIconClick"
      >
      </i>
      <template slot-scope="{ item }">
        <div class="name">{{ item.value }}</div>
        <span class="addr">{{ item.address }}</span>
      </template>
    </el-autocomplete>

    <!-- 数据展示区域 -->
    <el-autocomplete
      popper-class="my-autocomplete"
      v-model="stateword"
      :fetch-suggestions="querySearch"
      placeholder="请选择搜索的内容"
      @select="handleSelect"
      style="width: 180px"
    >
      <i
        class="el-icon-edit el-input__icon"
        slot="suffix"
        @click="handleIconClick"
      >
      </i>
      <template slot-scope="{ item }">
        <div class="name">{{ item.value }}</div>
        <span class="addr">{{ item.address }}</span>
      </template>
    </el-autocomplete>
    <el-button type="primary" icon="el-icon-search" @click="searchButton()"
      >搜索</el-button
    >
    <el-button type="primary" icon="el-icon-search" @click="showModal"
      >添加</el-button
    >

    <!-- 数据渲染区域 -->
    <div class="divshow" >
      <el-table stripe :data="tableData" style="width: 100%;" border>
        <el-table-column prop="imageUrl" label="新闻封面" width="120px">
          <template slot-scope="scope">
            <img :src="scope.row.imageUrl" alt="" style="width: 80px" />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="新闻标题" width="180px">
           </el-table-column>
        <el-table-column prop="author" label="新闻作者" width="120px">
        </el-table-column>
        <el-table-column prop="time" label="发布时间" width="250px" >
          <template slot-scope="scope">
            {{ scope.row.time }}
          </template>
        </el-table-column>

        <el-table-column prop="isOnline" label="是否发布" >
          <template slot-scope="scope">
            {{ scope.row.isOnline == 1 ? "已发布" : "未发布" }}
          </template>
        </el-table-column>
        <el-table-column prop="types" label="新闻类型" width="250px">
          <template slot-scope="scope">
            <el-tag
              type="success"
              v-for="item in scope.row.types"
              :key="item"
              >{{ item }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250px" >
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="editModal(scope.row)" width="250px"
              >编辑</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-delete"
              @click="removeModal(scope.row._id)" width="250px"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页信息 -->
    <div class="block">
      <span class="demonstration"></span>
      <el-pagination
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        @current-change="changePage"
      >
      </el-pagination>
    </div>

    <!-- 弹窗的内容 -->
    <el-dialog
      title="添加新闻"
      :visible.sync="dialogVisible"
      width="80%"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="新闻封面">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="新闻标题">
          <el-input v-model="form.title"></el-input>
        </el-form-item>

        <el-form-item label="新闻作者">
          <el-input v-model="form.author"></el-input>
        </el-form-item>

        <el-form-item label="发布日期">
          <el-col>
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="form.time"
              style="width: 100%"
              value-format="timestamp"
            ></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="是否发布">
          <el-switch
            v-model="form.isOnline"
            active-value="1"
            inactive-value="0"
          ></el-switch>
        </el-form-item>

        <el-form-item label="新闻类型">
          <el-checkbox-group v-model="form.types">
             <el-checkbox :label="item.text" name="type" v-for="item in type" :key="item.text">{{item.text}}</el-checkbox>
            <!-- <el-checkbox label="政治" name="type"></el-checkbox>
            <el-checkbox label="娱乐" name="type"></el-checkbox>
            <el-checkbox label="军事" name="type"></el-checkbox>
            <el-checkbox label="经济" name="type"></el-checkbox> -->
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="新闻正文">
          <quill-editor
            v-model="form.content"
            ref="myQuillEditor"
            :options="editorOption"
          >
          </quill-editor>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNewsSubmit" v-if="addHideButton"
          >确 定</el-button
        >
        <el-button type="primary" @click="editSubmit" v-if="editHideButton"
          >编辑</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import network from "@/network";
import { quillEditor, Quill } from "vue-quill-editor";
import { container, ImageExtend, QuillWatch } from "quill-image-extend-module";
import { formatDate } from "../util/date.js";

Quill.register("modules/ImageExtend", ImageExtend);
export default {
  data() {
    return {
      pageSize: 5,
      total: "",
      restaurants: [],
      statetype: "",
      stateword: "",
      tableData: [],
      dialogVisible: false,
      addHideButton: true,
      editHideButton: true,
      type:[],
      form: {
        title: "",
        author: "",
        time: "",
        isOnline: 0,
        content: "",
        imageUrl: "",
        types: [],
      },

      //编辑器插件
      editorOption: {
        modules: {
          ImageExtend: {
            loading: true,
            name: "img",
            action: "/api/upload",
            response: (res) => {
              return res.url;
            },
          },
          toolbar: {
            container: container,
            handlers: {
              image: function () {
                QuillWatch.emit(this.quill.id);
              },
            },
          },
        },
      },
      // content: '',
    };
  },
  methods: {
    //添加按钮事件
    showModal() {
      this.dialogVisible = true;
      this.addHideButton = true;
      this.editHideButton = false;
      console.log(this.editHideButton);
    },
    //添加新闻的网络请求
    async addNewsSubmit() {
      // console.log(this.editHideButton)
      let data = JSON.parse(JSON.stringify(this.form));
      console.log(261,data.types)
      data.types = JSON.stringify(data.types);
      let res = await network({
        url: "/news",
        method: "post",
        data,
      });
      console.log(268,res);
      this.dialogVisible = false;
      this.data = res.data;
      if (res.code == 0) {
        this.$message({
          message: "恭喜你，添加成功",
          type: "success",
        });
      } else {
        this.$message.error("错了哦，添加错误");
      }
      console.log(253, data);
      console.log(254, this.form);
      console.log("123");
    },
    //删除新闻的网络请求
    async removeModal(_id) {
      this.$alert("确认删除吗？", "警告", {
        confirmButtonText: "确定",
        callback: (action) => {
          this.$message({
            type: "info",
            message: `action: ${action}`,
          });
        },
      });
      let res = await network({
        url: "/news",
        method: "delete",
        data: {
          _id: _id,
        },
      });
      console.log(273, res);
      console.log(_id);
    },

    //编辑新闻的按钮
    editModal(editdata) {
      this.dialogVisible = true;
      this.form = editdata;
      console.log(288, this.form);
      console.log(289, this.form.time);
      this.addHideButton = false;
      this.editHideButton = true;
      let date = new Date();
      this.form.time = date.getTime();
      console.log(300, this.form.time);
    },
    // 确定编辑的网络请求
    async editSubmit() {
      let data = JSON.parse(JSON.stringify(this.form));
      data.types = JSON.stringify(data.types);
      let res = await network({
        url: "/news",
        method: "put",
        data,
      });
      console.log(res);
      this.dialogVisible = false;
      this.data = res.data;
      if (res.code == 0) {
        this.$message({
          message: "恭喜你，编辑成功",
          type: "success",
        });
      } else {
        this.$message.error("错了哦，编辑错误");
      }
    },
    //搜索新闻的按钮
    async searchButton() {
      console.log(341, this.stateword);
      console.log(342, this.statetype);
      let res = await network({
        url: "/news",
        method: "get",
        params: {
          page: 1,
          limit: this.pageSize,
          keywords: this.stateword,
          type: this.statetype,
        },
      });
      console.log(res);
       this.total=res.data.total
       this.tableData=res.data.rows
         this.tableData.map((item) => {
      item.time = formatDate(item.time / 1000);
      item.types = JSON.parse(item.types);
      return item;
    });
    },

    async changePage(page) {
      console.log(page);
      let res = await network({
        url: "/news",
        method: "get",
        params: {
          page: page,
          limit: this.pageSize,
        },
      });
      console.log(337, res);
      this.total = res.data.total;
      this.tableData = res.data.rows;
      this.tableData.map((item) => {
        item.time = formatDate(item.time / 1000);
        item.types = JSON.parse(item.types);
        return item;
      });
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },

    //搜索的数据
    loadAll() {
      return [
        {
          value: "title",
          // address:"新闻标题"
        },
        {
          value: "types",
          // address:"新闻类型"

        },
        {
          value:"author",
          // address: "作者",
        },
        // {
        //   value: "新旺角茶餐厅",
        //   address: "上海市普陀区真北路988号创邑金沙谷6号楼113",
        // },
   
      ];
    },
    handleSelect(item) {
      console.log(item);
    },
    handleIconClick(ev) {
      console.log(ev);
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },

    onSubmit() {
      console.log("submit!");
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw); 不能用本地图片
      this.form.imageUrl = res.url;
      // console.log(res)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },

  async mounted() {
    this.restaurants = this.loadAll();
    let res = await network({
      url: "/news",
      method: "get",
      params: {
        page: 1,
        limit: this.pageSize,
      },
    });
    console.log(466, res);
    this.total = res.data.total;
    this.tableData = res.data.rows;
    this.tableData.map((item) => {
      item.time = formatDate(item.time / 1000);
      item.types = JSON.parse(item.types);
      return item;
    });

      let res1 = await network({
      url: "/news/types",
      method: "get",
    });
    this.type=res1.data
console.log(482,this.type)
  },
};
</script>

<style lang="scss" scoped>
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
button {
  margin-left: 20px;
}

.block {
  text-align: right;
}

.avatar-uploader .el-upload {
  border: 1px dashed #0c0c0c;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed black;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>